
//
//  YTAppDelegate.m
//  YiTuDriverClient
//
//  Created by 石少庸 on 2017/4/26.
//  Copyright © 2017年 Yitu. All rights reserved.
//

#import "YTAppDelegate.h"
#import "YTUtilityManager.h"
#import "NSString+YTExtension.h"
#import "YTTabBarViewController.h"
#import "YTNavigationController.h"

#import <Bugly/Bugly.h>
#import <XGPush/XGPush.h>
#import <JPush/JPUSHService.h>
#import <UMMobClick/MobClick.h>
#import <RongIMKit/RongIMKit.h>
#import <RongIMLib/RongIMLib.h>
#import <UserNotifications/UserNotifications.h>

#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>

#import <AFNetworking/AFNetworking.h>

@interface YTAppDelegate ()<RCIMConnectionStatusDelegate, JPUSHRegisterDelegate>

@end

@implementation YTAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // window初始化
    [self windowInitWithRoot:application];
    
    // 一些三方lib的设置
    [self thirdLibsConfiguration:launchOptions];
    
    // 分享和支付相关
    [self configPayAndSharePlatform];
    
    // 推送注册
    [self registerAPNsWith:application];
    
    return YES;
}

#pragma mark - 初始化

// window初始化
- (void)windowInitWithRoot:(UIApplication *)application {
    [application setStatusBarHidden:NO];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    if ([[YTUtilityManager manager] getUserID]) {
        self.window.rootViewController = [[YTTabBarViewController alloc] init];
    } else {
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"YTLoginRegisterStoryboard" bundle:nil];
        YTNavigationController *login = [story instantiateViewControllerWithIdentifier:@"YTLoginRegister"];
        self.window.rootViewController = login;
    }
    [self.window makeKeyWindow];
}

// 分享和支付相关
- (void)configPayAndSharePlatform {
    // 推送初始化
    [XGPush startApp:2200192130 appKey:kPushKey];
    // 腾讯bugly
    BuglyConfig *config = [[BuglyConfig alloc] init];
    config.blockMonitorEnable = YES;
    config.viewControllerTrackingEnable = YES;
    config.unexpectedTerminatingDetectionEnable = YES;
    [Bugly startWithAppId:@"a8ff295824" config:config];
    // 容云聊天
    [[RCIM sharedRCIM] initWithAppKey:kRCKey];
    [[RCIM sharedRCIM] setConnectionStatusDelegate:self];
    // 友盟
    [self umengConfiguration];
}

// 配置umeng相关的东西
- (void)umengConfiguration {
    // 路径分析
    UMConfigInstance.appKey = kUMKey;
    UMConfigInstance.channelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    
    // app - trace,据说运营的要用
    NSString * appKey = kUMKey;
    NSString * deviceName = [[[UIDevice currentDevice] name] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString * mac = [NSString yt_getMacString];
    NSString * idfa = [NSString yt_getIdfaString];
    NSString * idfv = [NSString yt_getIdfvString];
    NSString * urlString = [NSString stringWithFormat:@"http://log.umtrack.com/ping/%@/?devicename=%@&mac=%@&idfa=%@&idfv=%@", appKey, deviceName, mac, idfa, idfv];
    [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL: [NSURL URLWithString:urlString]] delegate:nil];
}

// 三方库配置
- (void)thirdLibsConfiguration:(NSDictionary *)options {
    // svprogress
    [SVProgressHUD setMaximumDismissTimeInterval:1.5];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
    // 开启网络检测
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    // 高德地图
    [AMapServices sharedServices].apiKey = kAMapKey;
    
    // 极光推送
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService setBadge:0];
    JPUSHRegisterEntity *entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];

#warning 上架的时候一定要改成生产环境
    
    [JPUSHService setupWithOption:options
                           appKey:@"6deaf679915762a744b5e059"
                          channel:@"Development" apsForProduction:NO];
}

#pragma mark - APNs

- (void)registerAPNsWith:(UIApplication *)application {
    UIUserNotificationSettings *settings = [UIUserNotificationSettings
                                            settingsForTypes:(UIUserNotificationTypeBadge |
                                                              UIUserNotificationTypeSound |
                                                              UIUserNotificationTypeAlert)
                                            categories:nil];
    [application registerUserNotificationSettings:settings];
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    [application registerForRemoteNotifications];
}

// 注册APNs
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token =
    [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"
                                                           withString:@""]
      stringByReplacingOccurrencesOfString:@">"
      withString:@""]
     stringByReplacingOccurrencesOfString:@" "
     withString:@""];
    
    [[RCIMClient sharedRCIMClient] setDeviceToken:token];
    void (^successBlock)(void) = ^(void){
        //成功之后的处理
        NSLog(@"[XGPush Demo]register successBlock");
    };
    
    void (^errorBlock)(void) = ^(void){
        //失败之后的处理
        NSLog(@"[XGPush Demo]register errorBlock");
    };
    
    //注册设备
    NSString *tokenStr = [XGPush registerDevice:deviceToken successCallback:successBlock errorCallback:errorBlock];
    NSLog(@"%@", tokenStr);
    [[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:kDeviceToken];
    [[NSUserDefaults standardUserDefaults] synchronize];
    // 极光
    [JPUSHService registerDeviceToken:deviceToken];

}

// APNs注册失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}

#pragma mark - RCIM

// 当im连接出现问题时回调这个方法
- (void)onRCIMConnectionStatusChanged:(RCConnectionStatus)status {
    
}

#pragma mark - Applications

- (void)applicationWillResignActive:(UIApplication *)application {}
- (void)applicationDidEnterBackground:(UIApplication *)application {}
- (void)applicationWillEnterForeground:(UIApplication *)application {}
- (void)applicationDidBecomeActive:(UIApplication *)application {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}
- (void)applicationWillTerminate:(UIApplication *)application {}

@end
